<template>
	<div id="select" class="y-select" :style="{ width: `${width}px` }">
		<div class="title" @click="showOption" :style="{ height: `${height}px`, 'line-height': `${height}px` }">
			<span v-if="!curLabel" class="placeholder">{{ placeholder }}</span>
			<span v-else>{{ curLabel }}</span>
			<span class="icon">
				<span class="icon-xuanzeqishouqi lin" v-if="isShow"></span>
				<span class="icon-zhankai3 lin" v-else></span>

			</span>
		</div>
		<div class="option" v-show="isShow">
			<slot></slot>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			isShow: false, // 是否下拉
			curLabel: "", // 当前选中的文字
			curValue: "", // 当前选中的value
			options: [], //存储options值
		}
	},
	props: {
		width: { type: Number, default: 200 },
		height: { type: Number, default: 40 },
		model: { type: String },
		value: {
			// 接收父组件传入的value，名字必须value，这样父组件才能用v-model绑定
			type: [Number, String],
		},
		placeholder: { type: String, default: "请选择" },
	},
	provide() {
		return {
			select: this,
		}
	},
	watch: {
		// 当前选中项变化，触发input事件，父元素既可以使用v-model监听
		curValue() {
			this.$emit("input", this.curValue)
		},
	},
	mounted() {
		this.init()
	},
	methods: {
		init() {
      console.log('==========',this.options);
			// 与父组件传入的value对比，确定当前选中的curvalue
			const curOption = this.options.filter((item) => item["value"] == this.model)
      console.log(curOption,'curOption',this.value);
			if (curOption.length > 0) {
				this.curLabel = curOption[0].label
				this.curValue = curOption[0].value
			}
		},
		showOption() {
			this.isShow = !this.isShow
		},
	},
}
</script>

<style lang="less" scoped>
.y-select {
	color: #666;
	display: inline-block;
	.title {
		display: flex;
		justify-content: space-between;
		padding: 0 6px;
		border-radius: 4px;
		border: 1px solid #dcdfe6;
		box-sizing: border-box;
		color: #606266;
		outline: none;
		padding: 0 15px;
		cursor: pointer;
		transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
	}
	.title span {
		/* 一行显示，超长省略号 */
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.placeholder {
		color: #bbb;
	}
	.option {
		border: 1px solid #e4e7ed;
		border-radius: 4px;
		background-color: #fff;
		box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
		box-sizing: border-box;
		margin: 5px 0;
	}
	.icon {
		cursor: pointer;
	}
}
</style>
